package dao

import (
	"chat-room/http/dto"
	"github.com/jinzhu/gorm"
	"github.com/pkg/errors"
	"time"
)

type Room struct {
	Id        int       `json:"id" gorm:"primary_key" description:"自增主键"`
	Number    string    `json:"number" gorm:"column:number" description:"聊天室编号"`
	Name      string    `json:"name" gorm:"column:name" description:"聊天室名称"`
	IsDelete  int       `json:"is_delete" gorm:"column:is_delete" description:"是否删除"`
	CreatedAt time.Time `json:"create_at" gorm:"column:create_at" description:"创建时间"`
}

func (r *Room) TableName() string {
	return "chat_room_room"
}

/**
 * @Author: yang
 * @Description：获取聊天室列表
 * @Date: 2021/10/20 11:03
 */
func (r *Room) List(tx *gorm.DB, in dto.RoomListInput) ([]Room, error) {
	var list []Room
	// 数据查询
	if in.Keyword != "" {
		keyword := "%" + in.Keyword + "%"
		tx = tx.Where("number like ? ", keyword).Or("name like ?", keyword)
	}
	if err := tx.Where("is_delete = 0 ").Find(&list).Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return list, nil
}

/**
 * @Author: yang
 * @Description：添加聊天室--保存
 * @Date: 2021/10/25 13:56
 */
func (r *Room) Save(tx *gorm.DB) error {
	if err := tx.Save(r).Error; err != nil {
		return err
	}
	return nil
}

/**
 * @Author: yang
 * @Description：聊天室详情
 * @Date: 2021/10/25 15:24
 */
func (r *Room) Find(tx *gorm.DB, search *Room) (*Room, error) {
	out := &Room{}
	if err := tx.Where(search).Find(&out).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, errors.New("聊天室不存在")
		}
	}
	return out, nil
}
